import axios from 'axios'
import { Message,MessageBox  } from 'element-ui'
import { getToken } from '@/utils/auth'
import errorCode from '@/utils/errorCode'
import router from '@/router'
import qs from 'qs';

axios.defaults.headers['Content-Type'] = 'application/json;charset=utf-8'
// 创建axios实例
const service = axios.create({
  // axios中请求配置有baseURL选项，表示请求URL公共部分
  baseURL: process.env.VUE_APP_BASE_API_URL,
  // 超时
  timeout: 10000
})
// request拦截器
service.interceptors.request.use(config => {
  // 是否需要设置 token
  console.info("url="+config.url)
  const isToken = (config.headers || {}).isToken === false
  if (getToken() && !isToken) {
    config.headers['Authorization'] = 'Bearer ' + getToken() // 让每个请求携带自定义token 请根据实际情况自行修改
  }
  if(config.method ==='get'||config.method ==='delete'){
    config.paramsSerializer = function(params){
      console.info(qs.stringify(params,{arrayFormat:'repeat'}));
      return qs.stringify(params,{arrayFormat:'repeat'})
    }
  }
  return config
}, error => {
    console.log(error)
    Promise.reject(error)
})

// 响应拦截器
service.interceptors.response.use(res => {
    if(!(res.headers['content-type'].indexOf("application/json") != -1)){
      return res.data;
    }
    const code = res.data.code;
    // 未设置状态码则默认成功状态
    // 获取错误信息
    const message = errorCode[code]
    if (code === 0) {
      return res.data;
    } else {
      if(code === 810015){
        MessageBox.alert('请重新登陆', '提示', {
          confirmButtonText: '确定',
          callback: action => {
              router.replace({
                  path:'/redirect',
                  name: '/redirect',
                  replace: true
              })
          }
      });
      }else{
        Message({
          message: res.data.message,
          type: 'error'
        })
  
        return Promise.reject(new Error(message))
      }
    }
  },

  error => {
    Message({
      message: error.message,
      type: 'error',
      duration: 5 * 1000
    })
    return Promise.reject(error)
  }
)

export default service
